package verify.listener;

import com.appleyk.core.model.LicenseResult;
import com.appleyk.core.model.LicenseVerifyManager;
import com.appleyk.core.utils.CommonUtils;
import verify.config.LicenseVerifyProperties;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;


/**
 * @Author: WangYao
 * @description: <p>项目启动时安装证书&定时检测lic变化，自动更替lic</p>
 * @date: 2024-05-08 11:16
 */
public class LicenseVerifyInstallListener {

    public LicenseVerifyProperties licenseVerifyProperties;
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    private ScheduledFuture<?> scheduledFuture;


    // 启动定时任务
    public void startTimer() {
        scheduledFuture = scheduler.scheduleAtFixedRate(this::timer, 0, 5, TimeUnit.SECONDS);
    }
    // 停止定时任务
    public void stopTimer() {
        if (scheduledFuture != null) {
            scheduledFuture.cancel(false);
        }
    }
    /**
     * 文件唯一身份标识 == 相当于人类的指纹一样
     */
    private static String md5 = "";
    private static boolean isLoad = false;

    public static void LicenseVerifyInstall(LicenseVerifyProperties licenseVerifyProperties) {
        new LicenseVerifyInstallListener(licenseVerifyProperties);
    }

    public LicenseVerifyInstallListener(LicenseVerifyProperties licenseVerifyProperties) {
        // startTimer();
        this.licenseVerifyProperties = licenseVerifyProperties;
        if (CommonUtils.isNotEmpty(licenseVerifyProperties.getLicensePath())) {
            install();
            try {
                String readMd5 = getMd5(licenseVerifyProperties.getLicensePath());
                isLoad = true;
                if (LicenseVerifyInstallListener.md5 == null || "".equals(LicenseVerifyInstallListener.md5)) {
                    LicenseVerifyInstallListener.md5 = readMd5;
                }
            } catch (Exception e) {

            }
        }
    }


    /**
     * 5秒检测一次，不能太快也不能太慢
     */
    protected void timer()  {
        if (!isLoad) {
            return;
        }
        String readMd5 = null;
        try {
            readMd5 = getMd5(licenseVerifyProperties.getLicensePath());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 不相等，说明lic变化了
        if (!readMd5.equals(LicenseVerifyInstallListener.md5)) {
            install();
            LicenseVerifyInstallListener.md5 = readMd5;
        }

    }

    private void install() {
        System.out.println("++++++++ 开始安装证书 ++++++++");
        LicenseVerifyManager licenseVerifyManager = new LicenseVerifyManager();
        /** 走定义校验证书并安装 */
        LicenseResult result = licenseVerifyManager.install(licenseVerifyProperties.getVerifyParam());
        if (result.getResult()) {
            System.out.println("++++++++ 证书安装成功 ++++++++");
        } else {
            System.out.println("++++++++ 证书安装失败 ++++++++");
        }
    }

    /**
     * <p>获取文件的md5</p>
     */
    public String getMd5(String filePath) throws Exception {
        File file;
        String md5 = "";
        try {
            file = new File(filePath);
            if (file.exists()) {
                FileInputStream is = new FileInputStream(file);
                byte[] data = new byte[is.available()];
                is.read(data);
                md5 = calculateMD5(data);
                is.close();
            }
        } catch (FileNotFoundException e) {

        }
        return md5;
    }

    public static String calculateMD5(byte[] data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hashBytes = md.digest(data);

            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace(); // 处理异常，例如打印错误信息
            return null;
        }
    }

}
